package de.justphil.tcg.tcgclient;

import java.util.concurrent.TimeUnit;

import org.glassfish.grizzly.websockets.WebSocket;

public class HeartBeatingWebSocket extends Thread {

	//private volatile boolean running = false;
	private volatile boolean heartBeat = false;
	private byte[] nullByteArr;
	private long heartBeatInterval;
	private final WebSocket webSocket;
	
	public HeartBeatingWebSocket(WebSocket webSocket, long interval, TimeUnit intervalUnit) {
		this.webSocket = webSocket;
		heartBeatInterval = TimeUnit.MILLISECONDS.convert(interval, intervalUnit);
		nullByteArr = new byte[0];
	}
	
	
	
	@Override
	public synchronized void start() {
		//running		= true;
		heartBeat	= true;
		super.start();
	}



	@Override
	public void run() {
		System.out.println("["+getName()+"] Heart beat routine is about to run...");
		while(!this.isInterrupted()) {
			try {
				Thread.sleep(heartBeatInterval);
				
				if (heartBeat && webSocket.isConnected()) {
					//System.out.println("HEART BEAT!");
					webSocket.sendPong(nullByteArr);
				}
				else {
					//System.out.println("Skipping this period due to implicit payload heart beat.");
					heartBeat = true;
				}
			} catch (InterruptedException e) {
				System.out.println("["+getName()+"] I was interrupted!");
				this.interrupt();
			}
		}
	}
	
	public void stopHeartBeating() {
		if (!this.isAlive() || this.isInterrupted())
			return;
		
		System.out.println("Stopping heart beating by "+Thread.currentThread().getName()+"...");
		
		//running = false;
		heartBeat = false;
		if (this.isAlive() && !this.isInterrupted())
			this.interrupt();
	}
	
	public void send(String s) {
		heartBeat = false;
		
		if (webSocket.isConnected())
			webSocket.send(s);
	}

}
